package com.lfg.leetcode.leetcode100;


public class No117connect {

    public static void main(String[] args) {
        Node node = new Node(1);
        node.left = new Node(2);
        node.right = new Node(3);

//        node.left.left = new Node(4);
//        node.left.right = new Node(5);

        node.right.left = new Node(6);
        node.right.left.right = new Node(8);
        node.right.right = new Node(7);
        node.right.right.left = new Node(9);

        connect(node);
        System.out.println("[" + node + "]");
    }

    public static Node connect(Node root) {
        Node header = root;

        while (header != null) {
            Node last = header;
            Node next = null;
            header = null;
            while (last != null) {
                if (last.left != null) {
                    if (null == next) {
                        next = last.left;
                        header = next;
                    } else {
                        next.next = last.left;
                        next = next.next;
                    }
                }
                if (last.right != null) {
                    if (null == next) {
                        next = last.right;
                        header = next;
                    } else {
                        next.next = last.right;
                        next = next.next;
                    }
                }
                last = last.next;
            }
        }

        return root;
    }
}
